import { BrowserWindow, ipcMain } from 'electron/main'
// import runScript from './vm2'
import executeScript from './vm'
import { connectToServer } from '../opcua/opcuaClient'
import { ConnectRequest, ConnectResponse } from '../opcua/types'

export default function setupIPC(mainWindow: BrowserWindow): void {
  // IPC test
  ipcMain.on('ping', () => console.log('pong'))
  ipcMain.on('open-new-tab', (_, url) => {
    const win = new BrowserWindow({
      width: 800,
      height: 600,
      webPreferences: {
        nodeIntegration: true,
        contextIsolation: false
      }
    })
    win.loadURL(url)
  })
  // 监听前端请求执行 JS 代码
  ipcMain.handle('run-script', async (_event, script: string) => {
    // return runScript(script)
    return executeScript(script)
  })
  // 监听前端请求执行 JS 代码 move to installEngine.ts for standalone process
  // ipcMain.handle('execute-script', async (_event, script: string) => {
  //   return executeScript(script)
  // })

  ipcMain.handle(
    'opcua-connect',
    async (_event, args: ConnectRequest): Promise<ConnectResponse> => {
      try {
        await connectToServer(args.endpointUrl, args.nodeId, (value) => {
          mainWindow?.webContents.send('opcua-data-changed', value)
        })
        return { success: true }
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
      } catch (err: any) {
        return { success: false, message: err.message }
      }
    }
  )

  ipcMain.on('window-minimize', () => mainWindow.minimize())
  ipcMain.on('window-maximize', () => {
    if (mainWindow.isMaximized()) {
      mainWindow.unmaximize()
    } else {
      mainWindow.maximize()
    }
  })
  ipcMain.on('window-close', () => mainWindow.close())
}
